
// 获取ul父类盒子
const center = document.querySelector('.layout-center')
// 获取浏览器可是窗口的高度 不包含滚动条
const windowHeight = document.documentElement.clientHeight
// 获取ul的偏移量
const uloffsetTop = center.offsetTop
// 获取购物车列表
const cartbox = document.querySelector('.cart_shopping')
// 创建页数
let currentPage = 1
// 数据节流
let flag = true
// 购物车数据列表
let cartList = []
// 获取url传值
let username = getQueryVariable('name') 
 if(username){
    $('.top_left').css('display', 'none')
    $('.top_left_hide').css('display','block')
    $('.top_left_hide >li > p').html(username)

    $('.top_left_hide a').on('click',function(){
        $('.top_left').css('display', 'block')
        $('.top_left_hide').css('display','none')
        window.location.href="./index.html"
    })
 }
//  跳转到list 页面的链接
golist()
function golist(){
    $('.search > ul > li > a').on('click',function(){
        if(username){
            window.location.href = "http://www.yjf.com:8080/page/list.html?name="+username
        }else{
            window.location.href = "http://www.yjf.com:8080/page/list.html"
        }
    })
}
// 交互
Ajax()
function Ajax() {
    $.ajax({
        url: '/jm/GetHomeTodayLists/100/1',
        success: function (res) {
            let { message, list } = JSON.parse(res)
            if (message != true) {
                console.log('获取数据失败');
            }
            bindHtml(list)
            ajaxEvent(list)
        }
    })
}

window.onscroll = function () {
    // 获取浏览器卷去的高度 加上浏览器可是窗口的高度
    let scrollTop = parseInt((document.documentElement.scrollTop || document.body.scrollTop) + windowHeight)
    let ulHeight = center.offsetHeight + uloffsetTop
    if (scrollTop >= ulHeight && flag == true) {
        flag = false
        currentPage++
        Ajax()
    }
    //楼层显示和隐藏 
    if(document.documentElement.scrollTop >= 590 ){
        $('.home_nav_box').stop().fadeIn()
    } else if(document.documentElement.scrollTop < 590 ){

        $('.home_nav_box').stop().fadeOut()
    }
}

// 渲染页面
function bindHtml(list) {  
    let cart = list.slice(0, 9 * currentPage)
    var str = template('tmp', {
        list: cart
    })
    center.innerHTML = str
    flag = true
}

// 渲染完页面后的回调事件里绑定事件
function ajaxEvent(list) {
    // 商品移入显示加入购物车
    $('.layout-center').on('mouseenter ', "li", function (e) {
        e = e || window.event
        $(this).find('.commit_new').css('display', 'block')
    })
    $('.layout-center').on('mouseleave', "li", function (e) {
        e = e || window.event
        $(this).find('.commit_new').css('display', 'none')
    })
    //避免渲染时候的重新绑定事件,先解绑以前绑定的点击事件   
    $('.layout-center').off('click', '.commit_btn')
    // 加入购物车按钮绑定事件
    $('.layout-center').on('click', '.commit_btn', function (e) {
        e = e || window.event
        // 如果没登录,跳转到登录页面
        e.stopPropagation()
        if(!username){
            window.location.href="http://www.yjf.com:8080/page/login.html"
        }
        // 点击商品的index
        let index = $(this).parent().parent().index()
        let frg = false
        for (var i = 0; i < localStorage.length; i++) {
            if (index == localStorage.key(i)) {
                frg = true
            }
        }
        if (frg == true) {
            let zancun = JSON.parse(localStorage[index])
            // 数量+1
            zancun.report_number++
            // 再将数据封装到local里面
            localStorage.setItem(index, JSON.stringify(zancun));

        } else if (frg == false) {
            localStorage.setItem(index, JSON.stringify(list[index]));
        }
        $('.commit_btn').animate({
            opacity:'0.5'
        })
        console.log(JSON.parse(localStorage[index]));
        fillCartList()
        // 加入购物车动画
        donghua(e.pageX,e.pageY)
    })
        // 公共函数 去详情页
        goDetails('.layout-center',list)

        // 公共函数绑定去购物车页面的按钮
        goCart()


 
}

// 获取localStorage里面的数据放到cartList 初始化購物車列表
fillCartList()
function fillCartList() {
    cartList = []
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i)

        cartList.push(JSON.parse(localStorage[key]))
    }
    bindCart()
}
//  渲染购物车
function bindCart() {
    // 如果购物车里没货,不执行
    
    if (!cartList.length || username == false ) {
        console.log('空的购物车');
        cartbox.innerHTML = `
           <div class='kong'>
            购物车里还没有商品,<br>
            快去挑选心爱的商品吧~
           <div>
         `
    } else {
        
        let totalPrice = 0
        let num = 0
        // 渲染num 数量
        if(cartList.length){
            
            $('.num').css('display','block').html(cartList.length)
        }
        cartList.forEach(e => {
            let unitPrice = e.deal_global ? e.deal_global.price_home : e.deal_group.price_dis
            
            totalPrice += (e.report_number + 1) * unitPrice
            num += parseInt(e.report_number + 1)
        })
        
        var str = template('cart_tmp', {
            list: cartList,
            num: num,
            price: totalPrice

        })
        cartbox.innerHTML = str
    }
}

// 渲染二级菜单
bingNav()
function bingNav(){
    $.ajax({
        url:'/list/bindnav.php',
        dataType:'json',
        success:function(res){
            let {list} = res
            let arr = []
            list.forEach( e=>{
                if(!arr.includes(e.tager)){
                    arr.push(e.tager)
                }
            } )
            var str = template('tmp_nav', {
                list: list,
                arr:arr
            })
            $('.hide_nav').html(str)

        }   
    })


}
// 各种移入显示
hoverXianshi('.me_jm')
hoverXianshi('.right_more')
hoverXianshi('.shopping-cart')

hide_nav('nav')
function hide_nav(dom) {
    $(dom).on("mouseenter", function () {
        $('.hide_nav').stop().slideDown()
    })
    $(dom).on("mouseleave", function () {
        $('.hide_nav').stop().slideUp()
    })
}



// 轮播图
// 获取轮播图需要的元素
const lunbotubox = document.querySelector('.lunbotu')

const ulbox = document.querySelector('.lunbotu > ul')

const olbox = document.querySelector('.lunbotu > ol')

const btnleft = document.querySelector('.banner_left')
const btnright = document.querySelector('.banner_right')
//轮播图执行函数 
let index = 1
let lunboflag = true
let timer = 1
// 获取单个图片大小
let imgboxWidth = parseInt($(ulbox).find('li').css('width'))
lunInto()
function lunInto() {
    // 定义一个定时器
    // 点击冷却的开关
    // 执行函数 
    creatPoint()
    copyImg()
    timerStart()
    animateStop()
    event()
    // 切换页面 停止轮播
    changTab()
}
// 创建焦点函数
function creatPoint() {
    let length = ulbox.children.length
    const frg = document.createDocumentFragment()
    for (i = 0; i < length; i++) {
        var li = document.createElement('li')
        li.innerText = i + 1
        if (i === 0) li.classList.add('active')
        frg.appendChild(li)
    }
    olbox.appendChild(frg)
}
// 复制首尾图片
function copyImg() {

    let firstBox = ulbox.firstElementChild.cloneNode(true)
    let lastBox = ulbox.lastElementChild.cloneNode(true)
    ulbox.appendChild(firstBox)
    ulbox.insertBefore(lastBox, ulbox.firstChild)
    ulbox.style.left = -imgboxWidth + 'px'
}
// 重复利用的运动函数
function moveStart(){
    $(ulbox).animate({
        left: -index * imgboxWidth + 'px'
    }, 1500
    , function () {
        moveEnd()
        lunboflag = true 
     })
}
// 自动切换
function timerStart() {
    timer = setInterval(() => {
        index++
        moveStart()
    }, 2000)
}
// 移入暂停 移出开始
function animateStop() {
    $(lunbotubox).on('mouseenter', () => {
        clearInterval(timer)
    })
    $(lunbotubox).on('mouseleave', () => {
        timerStart()
    })
}

// 运动结束自动跳转到第一个
function moveEnd() {
    lunboflag = true
    if (index == ulbox.children.length - 1) {
        index = 1
        ulbox.style.left = -index * imgboxWidth + 'px'
    }
    if (index === 0) {
        index = ulbox.children.length - 2
        ulbox.style.left = -index * imgboxWidth + 'px'
    }

    // 焦点跟随
    // 用imgBox 获取长度不可以 为什么?
    for (let i = 0; i < olbox.children.length; i++) {
        olbox.children[i].className = ''
    }
    olbox.children[index - 1].className = 'active'
}
// 绑定点击事件
function event(){
    $('.banner_left').on('click',()=>{
        if(lunboflag == true){
            lunboflag = false
            index--
            moveStart()
        }
        }
      )
    $('.banner_right').on('click',()=>{
            if(lunboflag == true){
                lunboflag = false
                index++
                moveStart()
            }
        }
      )
    $('.lunbotu > ol').on('click','li',function(){
        if( lunboflag == true){
            lunboflag = false
            index = $(this).index() + 1
            moveStart()
        }
    })
    
}

// 切换页面 停止轮播
function changTab(){
    document.addEventListener('visibilitychange', () => {
        if(document.visibilityState == 'hidden'){
            clearInterval(timer)
        }
        if(document.visibilityState == 'visible'){
            timerStart()
        }
    })
}

// 楼层
const everydaysee = document.querySelector('.home_one')
const topLou = document.querySelector('.home_two')

$('.home_one').on('click',function(){
    window.scrollTo({
        top:590
    })
})
$('.home_two').on('click',function(){
    window.scrollTo({
        top:0
    })
})

// 搜索
const inp = document.querySelector('.inpt_search')
const ul = document.querySelector('.ul_search')

// 1. 绑定事件
inp.addEventListener('input', function () {

  const str = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=32646,1446,32532,32327,32351,32046,32115,31321,32618,32503,22159&wd=' + this.value + '&req=2&bs=%E7%88%B1%E5%A5%87%E8%89%BA&csor=6&cb=fn&_=1598517558259'
  const script = document.createElement('script')
  script.src = str
  document.body.appendChild(script)
  script.remove()


})

function fn(res) {
  if (!res.g) {
    ul.style.display = 'none'
    return
  }
  let str = ''
  res.g.forEach(item => {
    str += `
      <li>${ item.q }</li>
    `
  })
  ul.innerHTML = str
  ul.style.display = 'block'
// 绑定点击事件
  $(ul).on('click','li',function(){
       $('.inpt_search').val(this.innerHTML)
       $('.ul_search').slideUp()
  })
}

